﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.OleDb;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Text;
using System.Web;
using System.Xml;
using NLUNZ;

namespace NLUNZ
{
    public class Utility
    {
        public static DataSet ExcelToDataSet(string opnFileName)
        {
            //provider ACE.OLEDB.12.0 is for Excel 2007, but some hosting is not supported//
            //string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + opnFileName + ";Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\"";
            string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + opnFileName + ";Extended Properties=\"Excel 8.0;HDR=YES;IMEX=1\"";
            OleDbConnection conn = new OleDbConnection(strConn);
            string strExcel = "";
            OleDbDataAdapter myCommand = null;
            DataSet ds = new DataSet();
            strExcel = "select * from [sheet1$]";
            try
            {
                conn.Open();
                myCommand = new OleDbDataAdapter(strExcel, strConn);
                myCommand.Fill(ds, "dtSource");
                return ds;
            }
            catch (Exception ex)
            {
                string err = "导入出错：" + ex + ", 错误信息";
                return ds;
            }
            finally
            {
                conn.Close();
                conn.Dispose();
            }
        }
        public static bool IsExcel(string FileName)
        {

            try
            {
                //取得文件名(抱括路径)里最后一个"."的索引
                int intExt = FileName.LastIndexOf(".");
                //取得文件扩展名
                string strExt = FileName.Substring(intExt);
                if (strExt.ToLower() == ".xls" || strExt.ToLower() == ".xlsx")
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch
            {
                return false;
            }
        }
        public static string NewFileName(string FileName, string serverDestinationPath)
        {


            //这里自动根据日期和文件大小不同为文件命名,确保文件名不重复
            DateTime datNow = DateTime.UtcNow.AddHours(+12);
            //string strNewName = DateTime.Now.ToString("yyyyMMddHHmmss") + "_" + FileName ;
            string strNewName = datNow.ToString("yyyyMMddHHmmss") + "_" + FileName;
            string strPath = serverDestinationPath + strNewName;
            return strPath;
        }

        public static object LockingTarget = new object();

        public static void LogToFile(HttpServerUtility server, string message)
        {
            lock(LockingTarget)
            {
                string path = server.MapPath("~/Upload/Logs/log.txt");
                StreamWriter writer = new StreamWriter(path,true);
                writer.Write(String.Format("{0}:{1}",DateTime.UtcNow.AddHours(Utility.TimeZone()),message));
            }
        }
        public void LogToFile(string message)
        {
            lock (LockingTarget)
            {
                string path = @"D:\Hosting\4503735\html\Upload\Logs\log.txt";
                StreamWriter writer = new StreamWriter(path, true);
                writer.Write(String.Format("{0}:{1}", DateTime.UtcNow.AddHours(Utility.TimeZone()), message));
            }
        }

        public static void LogErrorToEventLog(string sSource, string sEvent)
        {
            if (!EventLog.SourceExists(sSource))
                EventLog.CreateEventSource(sSource, "Application");

            EventLog.WriteEntry(sSource, sEvent, EventLogEntryType.Error);
        }

        public static string GetKendoDateTime(DateTime? dateTime)
        {
            if (dateTime.HasValue)
                return dateTime.Value.ToString("dd/MM/yyyy HH:mm");
            return String.Empty;
        }

        public static DateTime? SetKendoDateTime(string kendoDateTime)
        {
            DateTime? result;
            if (string.IsNullOrEmpty(kendoDateTime))
                result = null;
            else
            {
                try
                {
                    CultureInfo info = new CultureInfo("en-NZ");
                    result = DateTime.Parse(kendoDateTime, info);
                }
                catch (Exception)
                {
                    return null;
                }
            }
            return result;
        }


        public static string ErrorHtml(string error)
        {
            return string.Format("<div class='error-message'><div class='error-icon'></div>{0}</div>", error);
        }

        public static string SuccessHtml(string error)
        {
            return string.Format("<div class='success-message'><div class='success-icon'></div>{0}</div>", error);
        }

        public static string InfoHtml(string error)
        {
            return string.Format("<div class='info-message'><div class='info-icon'></div>{0}</div>", error);
        }

        public static string WarningHtml(string error)
        {
            return string.Format("<div class='warning-message'><div class='warning-icon'></div>{0}</div>", error);
        }

        public static int TimeZone()
        {
            int zone = 12;
            string timezone = System.Configuration.ConfigurationManager.AppSettings["TimeZone"];
            int nz;
            if(int.TryParse(timezone, out nz))
            {
                zone = nz;
            }
            return zone;
        }
        public static int GetLogID()
        {
            DateTime dtCurrent = DateTime.UtcNow.AddHours(Utility.TimeZone());

            int logId = (dtCurrent.Year - 2000) * 100000000 + dtCurrent.Month * 1000000 + dtCurrent.Day * 10000 +
dtCurrent.Hour * 100 + dtCurrent.Minute;

            return logId;
        }
        public static DateTime GetDateTimeFromLogID(int logid)
        {
            DateTime dtCurrent = DateTime.UtcNow.AddHours(Utility.TimeZone());

            int year = logid / 100000000;
            int month = (logid - year * 100000000) / 1000000;
            int day = (logid - year * 100000000 - month * 1000000) / 10000;
            int hour = (logid - year * 100000000 - month * 1000000 - day * 10000) / 100;
            int minute = logid % 100;
            DateTime newdt = new DateTime(year + 2000, month, day, hour, minute, 0);

            return newdt;
        }
    }
}